package com.bkgy.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.ConverterKeyBuild;
import com.alibaba.excel.write.metadata.WriteSheet;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author ZhuHongKai
 * @version 1.0
 * @ClassName ExcelUtils
 * @date 2023/2/7 16:28
 */
public class ExcelUtils {

    public static void downloadExcel(String fileNames, HttpServletResponse response, Class<?> entityClass, List<?> listExcel) {
        // 创建日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
        String format = dateFormat.format(System.currentTimeMillis());
        String fileName =  fileNames + format;
        ExcelWriter excelWriter = null;
        try {
            ServletOutputStream outputStream = getOutputStream(fileName, response);
            // 创建工作薄
            excelWriter = EasyExcel.write(outputStream, entityClass).build();
            TimestampStringConverter converter = new TimestampStringConverter();
            excelWriter.writeContext().currentWriteHolder().converterMap().put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey()),converter);
            excelWriter.writeContext().currentWriteHolder().converterMap()
                    .put(ConverterKeyBuild
                            .buildKey(converter.supportJavaTypeKey(), converter.supportExcelTypeKey()),converter);
            // 创建表格
            WriteSheet writeSheet = EasyExcel.writerSheet(fileNames).build();
            excelWriter.write(listExcel,writeSheet);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    /**
     * 导出文件时为Writer生成OutputStream
     * @param fileName
     * @param response
     * @return
     */
    public static ServletOutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");// 设置文件流编码格式 不然中文会乱码
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }
}
